//调用sepolia上的代币合约进行存钱测试
//代币地址  0x4bff082a07c50724FEce17d9ecFC6dE1FF809722
//桥合约地址 0xfdf38b612aadb51042575a5f7aecf2e376ee4647

import Web3 from 'web3';
import { promises as fs } from 'fs';

const jsonData = await fs.readFile('./build/contracts/L1Bridge.json', 'utf-8');
const bridgeJson = JSON.parse(jsonData);
const bridgeAbi = bridgeJson.abi;
//console.log(bridgeAbi);

// 配置参数
const USER_ADDRESS = '0x4C59A2AA9F39554b9f8D474d70AA3A7cB2467771'; // 你的钱包地址 Accout7
const PRIVATE_KEY = '0x7196e384031bb4f6e3647ee2166c574c758e44c4c79907d23ac5a602a96f3340'; // 你的钱包私钥 Accout27
const RPC_URL = 'https://rpc.sepolia.org'; // 你的以太坊节点RPC URL
const BRIDGE_CONTRACT_ADDRESS = '0xfdf38b612aadb51042575a5f7aecf2e376ee4647'; // L1Bridge 合约地址
const TOKEN_CONTRACT_ADDRESS = '0x4bff082a07c50724FEce17d9ecFC6dE1FF809722'; // ERC20 代币合约地址

// Web3 设置
const web3 = new Web3(RPC_URL);

// 后续的 Web3 合约和交易操作
console.log('Web3 已成功连接:', web3.currentProvider.host);

// 代币 ABI 和 L1Bridge 合约 ABI
// const bridgeAbi = [
//     { "constant": false, "inputs": [{ "name": "amount", "type": "uint256" }], "name": "deposit", "outputs": [], "type": "function" },
//     { "anonymous": false, "inputs": [{ "indexed": true, "name": "user", "type": "address" }, { "indexed": false, "name": "amount", "type": "uint256" }, { "indexed": false, "name": "timestamp", "type": "uint256" }], "name": "Deposit", "type": "event" }
// ];

const erc20Abi = [
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }], "name": "balanceOf", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" },
    { "constant": false, "inputs": [{ "name": "spender", "type": "address" }, { "name": "amount", "type": "uint256" }], "name": "approve", "outputs": [{ "name": "", "type": "bool" }], "type": "function" },
    { "constant": true, "inputs": [{ "name": "owner", "type": "address" }, { "name": "spender", "type": "address" }], "name": "allowance", "outputs": [{ "name": "", "type": "uint256" }], "type": "function" }
];

async function cancelPendingTransaction() {
    // 获取当前账户的 nonce
    const nonce = await web3.eth.getTransactionCount(USER_ADDRESS, 'pending');

    console.log("nonce:", nonce);
    // 创建一个空交易，发送到自己的地址
    const cancelTx = {
        from: USER_ADDRESS,
        to: USER_ADDRESS, // 发送到自己的地址
        value: '0x0', // 发送 0 ETH
        gas: 21000, // 最小 gas 限制
        maxPriorityFeePerGas: web3.utils.toWei('5', 'gwei'), // 设置更高的优先费
        maxFeePerGas: web3.utils.toWei('100', 'gwei'), // 设置更高的最大费
        nonce: nonce // 使用相同的 nonce
    };

    // 签名交易
    const signedCancelTx = await web3.eth.accounts.signTransaction(cancelTx, PRIVATE_KEY);

    // 发送交易
    const receipt = await web3.eth.sendSignedTransaction(signedCancelTx.rawTransaction);
    console.log("取消交易已发送。交易哈希:", receipt.transactionHash);
}

async function main() {
    // 取消未确认的交易
    // await cancelPendingTransaction();

    // 创建钱包签名者
    const account = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);
    web3.eth.accounts.wallet.add(account);
    web3.eth.defaultAccount = account.address;

    // 创建 ERC20 代币合约实例
    const tokenContract = new web3.eth.Contract(erc20Abi, TOKEN_CONTRACT_ADDRESS);

    // 获取用户余额
    const balance = await tokenContract.methods.balanceOf(USER_ADDRESS).call();
    console.log(`当前余额: ${web3.utils.fromWei(balance, 'ether')} Tokens`);

    // 设置存款金额（例如 10 个代币）
    const depositAmount = web3.utils.toWei('7.7', 'ether'); // 存入 10 TOKEN

    // 检查是否已批准足够的代币给桥合约
    const allowance = await tokenContract.methods.allowance(USER_ADDRESS, BRIDGE_CONTRACT_ADDRESS).call();
    if (parseInt(allowance) < parseInt(depositAmount)) {
        console.log("批准代币给桥合约...");
        const approveTx = tokenContract.methods.approve(BRIDGE_CONTRACT_ADDRESS, depositAmount);
        const approveSignedTx = await web3.eth.sendTransaction({
            from: USER_ADDRESS,
            to: TOKEN_CONTRACT_ADDRESS,
            data: approveTx.encodeABI(),
            gas: 200000,
            maxPriorityFeePerGas: web3.utils.toWei('10', 'gwei'),
            maxFeePerGas: web3.utils.toWei('100', 'gwei'),
        });
        console.log("批准已完成。交易哈希:", approveSignedTx.transactionHash);
    } else {
        console.log("已批准足够的代币给桥合约。");
    }

    // 创建 L1Bridge 合约实例
    const bridgeContract = new web3.eth.Contract(bridgeAbi, BRIDGE_CONTRACT_ADDRESS);

    // 调用 deposit 函数
    console.log(`正在存入 ${web3.utils.fromWei(depositAmount, 'ether')} Tokens 到桥合约...`);
    const depositTx = bridgeContract.methods.deposit(depositAmount);
    const signedDepositTx = await web3.eth.sendTransaction({
        from: USER_ADDRESS,
        to: BRIDGE_CONTRACT_ADDRESS,
        data: depositTx.encodeABI(),
        gas: 200000,
    });
    console.log("存款已完成。交易哈希:", signedDepositTx.transactionHash);

    // 监听 Deposit 事件
    bridgeContract.events.Deposit({
        filter: { user: USER_ADDRESS },
        fromBlock: 'latest'
    })
    .on('data', (event) => {
        console.log("检测到存款事件:");
        console.log(`用户地址: ${event.returnValues.user}`);
        console.log(`存款金额: ${web3.utils.fromWei(event.returnValues.amount, 'ether')} Tokens`);
        console.log(`时间戳: ${new Date(Number(event.returnValues.timestamp) * 1000).toLocaleString()}`);
        console.log('-----------------------------');
    });
    //.on('error', console.error);

    console.log("监听 Deposit 事件中...");
}

main().catch(error => {
    console.error("发生错误:", error);
    process.exit(1);
});
